/**
 * @author banglong
 * @date 2016/10/28
 */
define(['text!../html/components/common/radioSelectDialogTemp.html!strip', 'avalon', 'selectDialogApi',
    'tools', 'Layer'
  ],
  function (htmlTemp, avalon, api, tools, layer) {

    return function () {
      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          layeroObj: -1,
          sourceData: [],
          timeObj: {}
        };
      };

      var selectVm;
      var getVmOption = function () {
        return {
          $id: 'radioSelect',
          header: [],
          row: [],
          sourceData: [],
          searchValue: '',

          hideLayer: function () {
            layer.close(runtimeParam.layeroObj);
          },

          handleSearch: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              runtimeParam.conditionParam.searchValue = selectVm.searchValue;
              var condition = runtimeParam.getConditionFunc(runtimeParam.conditionParam);
              runtimeParam.requestParam.condition = JSON.stringify(condition);
              getData(runtimeParam, selectVm);
            });
          },

          handleDBClick: function (data) {
            if (runtimeParam.choose) {
              runtimeParam.choose(data);
            }
            layer.close(runtimeParam.layeroObj);
          }
        };
      };

      function getData(runtimeParam, selectVm) {
        var loadIndex = layer.load();
        selectVm.searchValue = runtimeParam.conditionParam.searchValue;
        api.getData(runtimeParam.requestParam).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }

          var result = JSON.parse(jsonResult.result);
          selectVm.sourceData.splice(0, selectVm.sourceData.length);
          selectVm.sourceData.pushArray(result);
          layer.close(loadIndex);

          // 设置焦点 并且初始化查询值
          setTimeout(function () {
            document.querySelector('#searchInputForMoreSelect').focus();
          }, 300);
        })['catch'](function (ex) {
          layer.close(loadIndex);
          tools.handleError(ex);
        })
      }

      this.init = function (param) {
        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign(runtimeParam, param);

        runtimeParam.layeroObj = tools.createNewOpenWindow(['800px', '560px'], runtimeParam.title, htmlTemp,
          false, {
            vmConfig: getVmOption(),
            // 销毁方法
            destroy: function () {
              runtimeParam = null;
              selectVm = null;
            }
          });


        var vmOption = getVmOption();
        // 选中的数据重新加载 进选中的表格中
        vmOption.header = runtimeParam.header.concat();
        vmOption.row = runtimeParam.row.concat();
        selectVm = tools.initAvalonVm(avalon, vmOption, '.radio-select');

        getData(runtimeParam, selectVm);
      };
    };
  });